package com.geek.javase.ch14.work.lockwork;

/*
 *@author wangpeng
 *2025/10/30 16:44
 *@description TODO
 */
public class BankCard {
    private double balance;

    public BankCard(double initialBalance) {
        this.balance = initialBalance;
    }

    public synchronized void withdraw(double amount) {
        if (balance >= amount) {
            System.out.println(Thread.currentThread().getName() + " 正在取款: " + amount);
            balance -= amount; // 更新余额
            System.out.println(Thread.currentThread().getName() + " 取款成功，当前余额: " + balance);
        } else {
            System.out.println(Thread.currentThread().getName() + " 取款失败，余额不足");
        }
        if (balance == 0) {
            System.out.println("余额已归0，无法再进行取款");
        }
    }

    // 获取余额
    public synchronized double getBalance() {
        return balance;
    }

}

class WithdrawThread extends Thread {
    private BankCard account;
    private double amount;

    public WithdrawThread(BankCard account, double amount, String name) {
        super(name);
        this.account = account;
        this.amount = amount;
    }

    @Override
    public void run() {
        account.withdraw(amount);
    }
}

class BankTest {
    public static void main(String[] args) {
        BankCard account = new BankCard(1000);

        WithdrawThread t1 = new WithdrawThread(account, 500, "线程1");
        WithdrawThread t2 = new WithdrawThread(account, 600, "线程2");
        t1.start();
        t2.start();
    }
}